package handler

import (
	"context"
	"errors"

	"user-srv/basic/globar"
	__ "user-srv/basic/proto"
	"user-srv/model"
)

type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {

	return &__.LoginResp{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Videoadd(_ context.Context, in *__.VideoaddReq) (*__.VideoaddResp, error) {
	var v model.Video
	tx := globar.DB.Begin()
	v = model.Video{
		UserId: int(in.UserId),
		Title:  in.Title,
		Image:  in.Image,
		Info:   in.Info,
		Price:  in.Price,
		Num:    int(in.Num),
		Types:  int(in.Types),
		Status: int(in.Status),
	}
	if err := v.GetOnfile(globar.DB, in.Title); err != nil {
		tx.Rollback()
		return nil, errors.New("数据获取失败")
	}
	if err := v.Create(globar.DB); err != nil {
		tx.Rollback()
		return nil, errors.New("数据添加失败")
	}
	tx.Commit()
	return &__.VideoaddResp{
		Id: int64(v.ID),
	}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) VideoUpdate(_ context.Context, in *__.VideoUpdateReq) (*__.VideoUpdateResp, error) {
	var v model.Video
	// 开始事务
	tx := globar.DB.Begin()
	v = model.Video{
		UserId: int(in.UserId),
		Title:  in.Title,
		Image:  in.Image,
		Info:   in.Info,
		Price:  in.Price,
		Num:    int(in.Num),
		Types:  int(in.Types),
		Status: int(in.Status),
	}
	if err := v.GetOnfile(globar.DB, in.Title); err != nil {
		tx.Rollback()
		return nil, errors.New("数据获取失败")
	}
	if err := v.Update(globar.DB, int(in.Id)); err != nil {
		tx.Rollback()
		return nil, errors.New("数据修改失败")
	}
	tx.Commit()
	return &__.VideoUpdateResp{
		Id: int64(v.ID),
	}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	var v model.Video
	tx := globar.DB.Begin()
	getcover, err := v.Getcover(globar.DB)
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	return &__.VideoListResp{
		List: getcover,
	}, nil
}
